<template>
    <div class="person-list">
        <a-card title="人员名单管理" :bordered="false">
            <template #extra>
                <a-space>
                    <a-button @click="goBack">返回</a-button>
                    <a-upload accept=".csv,.xlsx" :show-upload-list="false" @change="handleImport">
                        <a-button type="primary">导入名单</a-button>
                    </a-upload>
                </a-space>
            </template>

            <!-- 搜索表单 -->
            <a-form layout="inline" :model="searchForm" class="search-form">
                <a-form-item label="姓名">
                    <a-input v-model:value="searchForm.name" placeholder="请输入姓名" allowClear />
                </a-form-item>
                <a-form-item label="身份证号码">
                    <a-input v-model:value="searchForm.idNumber" placeholder="请输入身份证号码" allowClear />
                </a-form-item>
                <a-form-item label="手机号码">
                    <a-input v-model:value="searchForm.phone" placeholder="请输入手机号码" allowClear />
                </a-form-item>
                <a-form-item label="抢票状态">
                    <a-select v-model:value="searchForm.ticketStatus" style="width: 120px" allowClear>
                        <a-select-option value="1">已抢票</a-select-option>
                        <a-select-option value="0">未抢票</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item>
                    <a-button type="primary" @click="handleSearch">搜索</a-button>
                    <a-button style="margin-left: 8px" @click="resetSearch">重置</a-button>
                </a-form-item>
            </a-form>

            <!-- 人员列表 -->
            <a-table :columns="columns" :data-source="personList" :loading="loading" :pagination="pagination"
                @change="handleTableChange">
                <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'ticketStatus'">
                        <a-tag :color="record.ticketStatus ? 'green' : 'red'">
                            {{ record.ticketStatus ? '已抢票' : '未抢票' }}
                        </a-tag>
                    </template>
                    <template v-if="column.key === 'action'">
                        <a-space>
                            <a @click="editPerson(record)">编辑</a>
                            <a-divider type="vertical" />
                            <a-popconfirm title="确定要删除这条记录吗？" @confirm="deletePerson(record)">
                                <a class="danger">删除</a>
                            </a-popconfirm>
                        </a-space>
                    </template>
                </template>
            </a-table>
        </a-card>

        <!-- 编辑人员信息对话框 -->
        <a-modal v-model:visible="editModalVisible" title="编辑人员信息" @ok="handleEditModalOk"
            @cancel="handleEditModalCancel">
            <a-form :model="editForm" :rules="editRules" ref="editFormRef">
                <a-form-item label="姓名" name="name">
                    <a-input v-model:value="editForm.name" />
                </a-form-item>
                <a-form-item label="身份证号码" name="idNumber">
                    <a-input v-model:value="editForm.idNumber" />
                </a-form-item>
                <a-form-item label="手机号码" name="phone">
                    <a-input v-model:value="editForm.phone" />
                </a-form-item>
                <a-form-item label="抢票状态" name="ticketStatus">
                    <a-switch v-model:checked="editForm.ticketStatus" />
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'

const route = useRoute()
const router = useRouter()
const taskId = route.params.taskId
const { proxy } = getCurrentInstance()

// 返回上一页
const goBack = () => {
    router.back()
}

// 表格列定义
const columns = [
    {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
    },
    {
        title: '身份证号码',
        dataIndex: 'idNumber',
        key: 'idNumber',
    },
    {
        title: '手机号码',
        dataIndex: 'phone',
        key: 'phone',
    },
    {
        title: '抢票状态',
        dataIndex: 'ticketStatus',
        key: 'ticketStatus',
    },
    {
        title: '操作',
        key: 'action',
    },
]

// 搜索表单
const searchForm = reactive({
    name: '',
    idNumber: '',
    phone: '',
    ticketStatus: undefined,
})

// 分页配置
const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showTotal: (total) => `共 ${total} 条`,
})

// 加载状态
const loading = ref(false)

// 人员列表数据
const personList = ref([
    {
        key: '1',
        name: '张三',
        idNumber: '110101199001011234',
        phone: '13800138000',
        ticketStatus: true,
    },
    {
        key: '2',
        name: '李四',
        idNumber: '110101199001011235',
        phone: '13800138001',
        ticketStatus: false,
    },
])

// 编辑模态框状态
const editModalVisible = ref(false)
const editFormRef = ref(null)

// 编辑表单数据
const editForm = reactive({
    key: '',
    name: '',
    idNumber: '',
    phone: '',
    ticketStatus: false,
})

// 编辑表单验证规则
const editRules = {
    name: [{ required: true, message: '请输入姓名' }],
    idNumber: [{ required: true, message: '请输入身份证号码' }],
    phone: [{ required: true, message: '请输入手机号码' }],
}

// 处理搜索
const handleSearch = () => {
    pagination.current = 1
    fetchData()
}

// 重置搜索
const resetSearch = () => {
    searchForm.name = ''
    searchForm.idNumber = ''
    searchForm.phone = ''
    searchForm.ticketStatus = undefined
    handleSearch()
}

// 处理表格变化
const handleTableChange = (pag) => {
    pagination.current = pag.current
    pagination.pageSize = pag.pageSize
    fetchData()
}

// 获取数据
const fetchData = async () => {
    loading.value = true
    try {
        const res = await proxy.$http.get(`/person-list/${taskId}`, {
            params: {
                ...searchForm,
                page: pagination.current,
                pageSize: pagination.pageSize
            }
        })
        personList.value = res.list
        pagination.total = res.total
    } catch (error) {
        console.error('获取数据失败：', error)
    } finally {
        loading.value = false
    }
}

// 处理导入
const handleImport = async (info) => {
    if (info.file.status === 'uploading') {
        return
    }
    if (info.file.status === 'done') {
        try {
            const formData = new FormData()
            formData.append('file', info.file.originFileObj)
            await proxy.$http.post(`/person-list/${taskId}/import`, formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            })
            message.success('导入成功')
            fetchData()
        } catch (error) {
            message.error('导入失败')
        }
    }
}

// 编辑人员信息
const editPerson = (record) => {
    Object.assign(editForm, record)
    editModalVisible.value = true
}

// 删除人员信息
const deletePerson = async (record) => {
    try {
        await proxy.$http.delete(`/person-list/${taskId}/${record.key}`)
        message.success('删除成功')
        fetchData()
    } catch (error) {
        message.error('删除失败')
    }
}

// 处理编辑模态框确认
const handleEditModalOk = async () => {
    try {
        await editFormRef.value.validate()
        await proxy.$http.put(`/person-list/${taskId}/${editForm.key}`, editForm)
        editModalVisible.value = false
        message.success('保存成功')
        fetchData()
    } catch (error) {
        if (error.name === 'ValidationError') {
            return
        }
        message.error('保存失败')
    }
}

// 处理编辑模态框取消
const handleEditModalCancel = () => {
    editModalVisible.value = false
}

// 页面加载时获取数据
onMounted(() => {
    fetchData()
})
</script>

<style scoped>
.person-list {
    padding: 24px;
}

.search-form {
    margin-bottom: 24px;
}

.danger {
    color: #ff4d4f;
}
</style>